package data.render;

import java.awt.Color;

import data.base.PointLight;
import data.base.Vector3;
import data.complex.Boundary;
import data.complex.Ray;
import data.complex.Triangle;
import data.complex.VoxelSpace;
import data.hierarchy.Mesh;
import data.hierarchy.TriangleGroup;
import data.hierarchy.World;



public class FastPhongRenderMethod implements IRenderMethod{
  private World world;
  private VoxelSpace vs;
  
  public FastPhongRenderMethod(World world){
    this.world = world;  
    vs = new VoxelSpace(new Boundary(world));    
    refresh();
  }
  
  public void refresh(){
    for(Mesh m : world.getMeshes())
      for(TriangleGroup tg : m)
        for(Triangle t : tg)
          vs.registerTriangle(t);
  }

  @Override
  public Color getPixel(Ray ray) {
    vs.calculateFirstTriangleIntersection(ray, Double.MAX_VALUE, null);
    if(ray.getIntersection().isIntersecting()){
      int red = 0;
      int green = 0;
      int blue = 0;
      for(PointLight light : world.getPointLights()){
        Vector3 a = new Vector3(ray.getIntersection(), light);
        a.normalize();
        double brightness = 
          Math.max(0, a.getDotProduct(ray.getIntersection().getNormal())) * 
          light.getIntensity();
        red += light.getColor().getRed() * brightness;
        green += light.getColor().getGreen() * brightness;
        blue += light.getColor().getBlue() * brightness;
      }
      return new Color(
          Math.min(255, red),
          Math.min(255, green),
          Math.min(255, blue));
    }
    return Color.BLACK;
  }
  
  public VoxelSpace getVoxelSpace(){
    return vs;
  }
}
